﻿using com.tanlingyun.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.tanlingyun.baojia.Entity;

namespace com.tanlingyun.DbServices
{
    public class RawService:BaseService
    {
        /// <summary>
        /// 添加原材料
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="material"></param>
        /// <returns></returns>
        public OperateResult AddRaw(int user_id,RawMaterials material)
        {
            material.status = 1;
            if (material.time == DateTime.MinValue) material.time = DateTime.Now;

            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "用户信息错误，请重新登录！" };
            if (entityUser.level_type == (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "无权限！" };
            else if (entityUser.level_type == (int)ELevelType.Admin)
                material.manager_id = 0;
            else if (entityUser.level_type == (int)ELevelType.Manager)
                material.manager_id = entityUser.id;

            if (db.Insert<RawMaterials>("RawMaterials", material).AutoMap(x => x.id).ExecuteReturnLastId<int>() > 0)
                return new OperateResult() { code = ResultCode.Success};
            return new OperateResult() { code = ResultCode.Failed,message = "添加失败!" };
        }

        /// <summary>
        /// 获取原材料分页
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="search"></param>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="manager_id">分管理员</param>
        /// <returns></returns>
        public PageInfo<RawMaterials> GetRawList(int user_id,string search="",int PageIndex = 1,int PageSize = 10,int manager_id = 0)
        {
            PageInfo<RawMaterials> rawPage = new PageInfo<RawMaterials>()
            {
                Fields = "*",
                TableName = "RawMaterials",
                PageIndex = PageIndex,
                PageSize = PageSize,
                OrderBy = "time desc,name asc"
            };

            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant != 1)
                return rawPage;

            string where = "status=1 ";
            if (entityUser.level_type == (int)ELevelType.Operator)
                where += " and manager_id=" + entityUser.parentid;
            else if (entityUser.level_type == (int)ELevelType.Admin)
                where += " and manager_id=" + manager_id;
            else
                where += " and manager_id=" + entityUser.id;

            if (!string.IsNullOrWhiteSpace(search))
                where += " and (name like '%"+search+ "%' or alias like '%" + search + "%' or guige like '%" + search + "%')";
            rawPage.Where = where;
            return GetPageInfo<RawMaterials>(rawPage);
        }

        /// <summary>
        /// 删除原材料
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="raw_id"></param>
        /// <returns></returns>
        public OperateResult DeleteItem(int user_id,int raw_id)
        {
            RawMaterials raw = GetRaw(raw_id);
            if (raw == null || raw.status != 1)
                return new OperateResult() { code = ResultCode.Failed, message = "删除对象不存在!" };

            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant != 1)
                return new OperateResult() { code = ResultCode.Failed,message = "用户信息有误，请重新登录！" };

            if (entityUser.level_type == (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "无权限!" };
            else if (entityUser.level_type == (int)ELevelType.Manager && raw.manager_id != entityUser.id)
                return new OperateResult() { code = ResultCode.Failed,message = "无法删除非分管理员的数据！" };

            //if (db.Delete<RawMaterials>("RawMaterials", raw).Where(x => x.id).Execute() > 0)
            //    return new OperateResult() { code = ResultCode.Success };
            raw.status = 0;
            if (db.Update<RawMaterials>("RawMaterials", raw).Column(x => x.status).Where(x => x.id).Execute() > 0)
                //if (db.Delete<RawMaterials>("RawMaterials", raw).Where(x => x.id).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };

            return new OperateResult() { code = ResultCode.Failed,message  =  "删除失败!" };
        }

        /// <summary>
        /// 修改原材料
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="materials"></param>
        /// <returns></returns>
        public OperateResult UpdateItem(int user_id, RawMaterials materials)
        {
            UserService _userService = new UserService();
            User entityUser = _userService.GetUser(user_id);
            if (entityUser == null || entityUser.status != 1 || entityUser.isgrant != 1)
                return new OperateResult() { code = ResultCode.Failed,message = "用户信息有误，请重新登录！" };

            RawMaterials entityRaw = GetRaw(materials.id);
            if (entityRaw == null)
                return new OperateResult() { code = ResultCode.Failed, message = "原材料不存在！" };

            if (entityUser.level_type == (int)ELevelType.Operator)
                return new OperateResult() { code = ResultCode.Failed, message = "无权限!" };
            else if (entityUser.level_type == (int)ELevelType.Manager && entityRaw.manager_id != entityUser.id)
                return new OperateResult() { code = ResultCode.Failed, message = "无法更新非分管理员的数据！" };

            if (db.Update<RawMaterials>("RawMaterials", materials).AutoMap(x => x.id,x=>x.status,x=>x.manager_id).Where(x => x.id).Execute() > 0)
                return new OperateResult() { code = ResultCode.Success };
            return new OperateResult() { code = ResultCode.Failed, message = "修改失败!" };
        }

        /// <summary>
        /// 解析上传的文件
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public OperateResult AnalysisRawData(int user_id,string file)
        {
            string path = System.Web.HttpContext.Current.Server.MapPath("/") + file;
            if (string.IsNullOrWhiteSpace(file) || !System.IO.File.Exists(path))
                return new OperateResult() { code = ResultCode.Failed, message = "未获取到文件！" };
            //解析文件
            try
            {
                var excel = new LinqToExcel.ExcelQueryFactory(path);
                var sheet = excel.Worksheet(0);
                var query = from p in sheet select p;

                IList<RawMaterials> rawlist = new List<RawMaterials>();
                string error = "";

                int nindex = 0;
                foreach (var item in query)
                {
                    nindex++;
                    //材料名称	规格	单价	退废料单价	比重	 日期	拼音助记符
                    RawMaterials raw = new RawMaterials();
                    //解析产品名称
                    if (item[0].Value != null)
                        raw.name = item[0].Value.ToString();
                    if (string.IsNullOrWhiteSpace(raw.name) || raw.name.Length > 50)
                    {
                        error += string.Format("第{0}行名称不能为空且长度不能超过50个字符！<br/>", nindex);
                        continue;
                    }
                    //解析产品规格
                    if (item[1].Value != null)
                        raw.guige = item[1].Value.ToString();
                    if (!string.IsNullOrWhiteSpace(raw.guige) && raw.guige.Length > 50)
                    {
                        error += string.Format("第{0}行产品规格长度不能超过50个字符！<br/>", nindex);
                        continue;
                    }
                    //解析产品单价
                    decimal money = 0;
                    if (item[2].Value != null)
                        if (decimal.TryParse(item[2].Value.ToString(), out money))
                        {
                            raw.price = money;
                        }
                        else
                        {
                            error += string.Format("第{0}行产品单价不能为空且必须为数字！<br/>", nindex);
                            continue;
                        }
                    //解析退废料单价
                    if (item[3].Value != null)
                        if (decimal.TryParse(item[3].Value.ToString(), out money))
                        {
                            raw.tfl_price = money;
                        }
                        else
                        {
                            error += string.Format("第{0}行产品退废料单价不能为空且必须为数字！<br/>", nindex);
                            continue;
                        }
                    //检查比重
                    if (item[4].Value != null)
                        if (decimal.TryParse(item[4].Value.ToString(), out money))
                        {
                            raw.bizhong = (float)money;
                        }
                        else
                        {
                            error += string.Format("第{0}行产品比重必须为数字！<br/>", nindex);
                            continue;
                        }
                    //检查日期
                    DateTime dt = DateTime.MinValue;
                    if (item[5].Value != null)
                        if (DateTime.TryParse(item[5].Value.ToString(), out dt))
                        {
                            raw.time = dt;
                        }
                        else
                        {
                            error += string.Format("第{0}行时间格式必须为yyyy-mm-dd，如2017-10-01！<br/>", nindex);
                            continue;
                        }
                    //检查拼音助记符
                    if (item[6].Value != null)
                        raw.alias = item[6].Value.ToString();
                    if (!string.IsNullOrWhiteSpace(raw.alias) && raw.alias.Length > 50)
                    {
                        error += string.Format("第{0}行拼音助记符长度不能超过50个字符！<br/>", nindex);
                        continue;
                    }
                    rawlist.Add(raw);
                    OperateResult result = AddRaw(user_id, raw);
                    if (result.code != ResultCode.Success)
                        error += string.Format("第{0}行添加失败，错误信息是：" + result.message);
                    
                }
                if (rawlist.Count == 0)
                    return new OperateResult() { code = ResultCode.Failed, message = "未获取到数据" + (string.IsNullOrWhiteSpace(error) ? "" : "错误信息：<br/>" + error) };
                else
                {
                    return new OperateResult() { code = ResultCode.Success, message = "结果：成功{0}行，失败{1}行" + (string.IsNullOrWhiteSpace(error) ? "" : "，错误信息：<br/>" + error) };
                }
            }
            catch(Exception ex)
            {
                //ToDO 添加日志
                Log log = new Log() { user_id = user_id, data = ex.Message, detail = ex.StackTrace, time = DateTime.Now };
                AddLog(log);
            }
            return new OperateResult() { code = ResultCode.Failed, message = "解析失败！" };
        }

        /// <summary>
        /// 获取原材料
        /// </summary>
        /// <param name="raw_id"></param>
        /// <returns></returns>
        public RawMaterials GetRaw(int raw_id)
        {
            return db.Sql("select * from RawMaterials where id=@0",raw_id).QuerySingle<RawMaterials>();
        }
    }
}
